package com.example.demo.util.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description:日期时间反序列化
 * @create: 2018-07-06 09:36
 **/
@Slf4j
public class CustomDateDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
        String date = jsonParser.getText();
        try {
            if (date.length() == 19) {
                return formatDateTime.parse(date);//转时分秒
            } else if (date.length() == 10) {
                return formatDate.parse(date);//转日期
            } else {
                return null;
            }
        } catch (ParseException e) {
            log.error("parse date error {}", date, e);
            return null;
        }
    }
}
